package com.zrkizzy.system.api.common;

import com.wf.captcha.ArithmeticCaptcha;
import com.zrkizzy.common.core.domain.response.Result;
import com.zrkizzy.common.core.utils.IdUtil;
import com.zrkizzy.common.limit.annotation.AccessLimit;
import com.zrkizzy.common.models.vo.common.captcha.CaptChaVO;
import com.zrkizzy.common.redis.service.IRedisService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.zrkizzy.common.core.constant.TimeConst.FIVE_MINUTE;
import static com.zrkizzy.common.redis.enums.RedisKey.CAPTCHA_KEY;
import static com.zrkizzy.module.system.constant.AccessLimitKey.GET_CAPTCHA;


/**
 * 验证码控制器
 *
 * @author zhangrongkang
 * @since 2023/4/13
 */
@Tag(name = "验证码控制器")
@RestController
@RequestMapping("/common/captcha")
public class CaptchaController {
    @Autowired
    private IdUtil idUtil;
    @Autowired
    private IRedisService redisService;

    @Operation(summary = "生成验证码")
    @GetMapping("/getCaptcha")
    @AccessLimit(key = GET_CAPTCHA, timeout = 1, max = 5)
    public Result<CaptChaVO> getCaptcha() {
        // 生成算数类型验证码
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(140, 28, 3);
        String traceId = String.valueOf(idUtil.nextId());
        // Redis存储验证码，过期时间为5分钟
        redisService.set(CAPTCHA_KEY.getKey() + traceId, captcha.text(), FIVE_MINUTE);
        return Result.ok(CaptChaVO.builder()
                // 验证码图片Base64编码
                .codeImage(captcha.toBase64())
                // 验证码唯一值
                .traceId(traceId).build());
    }

}
